using System;
using System.Collections;
using System.Data;
using System.Web.UI;
using Ventigrate.Shared.ExternalMembership.Internal;
using SWS = System.Web.Security;


namespace Ventigrate.Shared.ExternalMembership.WebControls
{
    /// <summary>
    /// Data source for the User Management user display view. Gets all FBA users and adds basic membership info 
    /// </summary>
    class FBAUsersView : DataSourceView
    {
        private ExtranetContext _ctx = null;
        internal ExtranetContext Ctx
        {
            get
            {
                if (null == _ctx)
                    _ctx = ExtranetContext.Default;

                return _ctx;
            }
        }

        public FBAUsersView(IDataSource owner, string viewName) : base(owner, viewName) { }

        [SPDisposeCheck.SPDisposeCheckIgnore(SPDisposeCheck.SPDisposeCheckID.SPDisposeCheckID_140, "RootWeb disposed automatically")]
        protected override IEnumerable ExecuteSelect(DataSourceSelectArguments selectArgs)
        {
            // only continue if a membership provider has been configured
            if (Ctx.MembershipProvider == null)
                return null;

            DataTable dt = new DataTable();
            dt.Columns.Add("Username");
            dt.Columns.Add("Email");
            dt.Columns.Add("Description");
            dt.Columns.Add("Active");
            dt.Columns.Add("Locked");
            dt.Columns.Add("Created");
            dt.Columns.Add("LastLogin");

            foreach (SWS.MembershipUser user in Membership.GetAllUsers())
            {
                //Add member to the data table
                DataRow dr = dt.NewRow();
                dr["Username"] = user.UserName;
                dr["Email"] = user.Email;
                dr["Description"] = user.Comment;
                dr["Active"] = user.IsApproved ? "Yes" : "No";
                dr["Locked"] = user.IsLockedOut ? "Yes" : "No";
                dr["Created"] = user.CreationDate;
                dr["LastLogin"] = user.LastLoginDate;
                dt.Rows.Add(dr);
            }

            // sort if a sort expression available
            DataView dataView = new DataView(dt);
            if (selectArgs.SortExpression != String.Empty)
            {
                dataView.Sort = selectArgs.SortExpression;
            }

            // return as a DataList            
            return (IEnumerable)dataView;
        }
    }
}